package com.github.icloudpay.pay.core.service.payForAnother;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import com.github.icloudpay.pay.core.biz.PayForAnotherOrderBiz;
import com.github.icloudpay.pay.core.entity.PayForAnotherOrder;
import com.github.icloudpay.pay.core.feign.CallBackFeign;
import com.github.wxiaoqi.security.common.admin.pay.request.CallbackRequest;
import com.github.wxiaoqi.security.common.admin.pay.request.CompleteTradeRequest;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;

/**
 * 代付回调
 * @author hexufeng
 *
 */
@EnableAsync
@Service("payForAnotherCallBackService")
public class PayForAnotherCallBackService {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(PayForAnotherCallBackService.class);

	@Autowired
	private PayForAnotherOrderBiz payForAnotherOrderBiz;
	@Autowired
	private AmqpTemplate rabbitTemplate;

	public void callBack(CallbackRequest callbackRequest){

		logger.info("代付回调开始：请求号{},交易状态{},",callbackRequest.getRequestNo(),callbackRequest.getStatus());

		PayForAnotherOrder payForAnotherOrder = new PayForAnotherOrder();
		payForAnotherOrder.setOutOrderNo(callbackRequest.getRequestNo());
		PayForAnotherOrder selectPayForAnotherOrder = payForAnotherOrderBiz.selectOne(payForAnotherOrder);
		if(selectPayForAnotherOrder == null){
			logger.error("代付订单不存在{}",callbackRequest.getRequestNo());
			return ;
		}

		//已成功，不需要处理
		if("00".equals(selectPayForAnotherOrder.getTxStatus())){
			logger.info("代付回调已处理，不需要再次处理：请求号{},回调状态{}",callbackRequest.getRequestNo(),selectPayForAnotherOrder.getTxStatus());
			return ;
		}
		//已失败，不需要处理
		if("01".equals(selectPayForAnotherOrder.getTxStatus())){
			logger.info("代付回调已处理，不需要再次处理：请求号{},回调状态{}",callbackRequest.getRequestNo(),selectPayForAnotherOrder.getTxStatus());
			return ;
		}

		if("00".equals(callbackRequest.getStatus())){
			selectPayForAnotherOrder.setTxStatus("00");//代付成功
		}else{
			selectPayForAnotherOrder.setTxStatus("01");//代付失败
		}
		payForAnotherOrderBiz.updateById(selectPayForAnotherOrder);

		//feign异步通知商户退款结果
		CompleteTradeRequest completeTradeRequest = new CompleteTradeRequest();
		completeTradeRequest.setAmount(String.valueOf(selectPayForAnotherOrder.getAmount()));
		completeTradeRequest.setOrderNo(selectPayForAnotherOrder.getOrderId());
		completeTradeRequest.setPlatformId(selectPayForAnotherOrder.getPlatformId());
		completeTradeRequest.setTradeType("3");//代付
		if("00".equals(callbackRequest.getStatus())){
			completeTradeRequest.setTxStatus("00");
		}else{
			completeTradeRequest.setTxStatus("01");
		}
		
		Map<String, Object> callBackResponse = new HashMap<String, Object>();
		int i = 0;
		do {
			i++;
			if (i > 2) // 如果通知失败，尝试重新通知3次
				break;
			try { // 通知商户
				logger.info("通知商户信息---request{}",EntityUtils.beanToMap(completeTradeRequest));
//				callBackResponse = callBackFeign.callBack(completeTradeRequest);
				String context = EntityUtils.beanToMap(completeTradeRequest).toString();
				this.rabbitTemplate.convertAndSend("topic.payment", context);
			} catch (Exception e) {
				logger.error("通知商户信息失败", e);
			}
		} while (callBackResponse != null && ResponseCode.OK.getCode().equals(callBackResponse.get("code")));
		
		logger.info("代付回调结束");
	}

}
